import { reactive } from "vue";
import { computed, StyleValue, CSSProperties } from "vue";

function worldWrap(world: string) {
  // 处理空白字符串，返回一个正经点的字符。避免开头是空白字符导致的测量的问题。
  if (/\s/.test(world)) {
    return "国";
  }
  return world;
}

/**
 * 检查代码是否在一行
 * @param text
 * @param style
 * @returns Boolean
 */
function useIsTextWrap(text: string, style: CSSProperties) {
  console.log(`text:${text},len:${text.length}`);
  const tmpDiv = document.createElement("div");

  Object.keys(style).forEach((key: any) => {
    tmpDiv.style[key] = style[key as keyof CSSProperties] as string;
  });
  tmpDiv.style.position = "fixed";
  tmpDiv.style.left = "0px";
  tmpDiv.style.top = "999999px";
  tmpDiv.style.boxSizing = "box-size";
  tmpDiv.style.visibility = "hidden";
  document.body.appendChild(tmpDiv);
  let prevClientHeight;
  for (let i = 0; i < text.length; i++) {
    tmpDiv.textContent += worldWrap(text[i]);
    const clientHeight = tmpDiv.clientHeight;
    if (prevClientHeight != void 0 && clientHeight > prevClientHeight) {
      console.log("tmpDiv.textContent-->", tmpDiv.textContent);
      tmpDiv.remove();
      return true;
    }
    prevClientHeight = clientHeight;
  }
  tmpDiv.remove();
  return false;
}
/**
 * 通过传入的样式，预先计算是否换行，如果换行了，那么就循环减直到合适为止。并返回合适的字体大小
 * @param wraplyric
 * @param style
 * @returns
 */
export function useAutoOneLineFontSize(wraplyric: string[], style: any) {
  while (true) {
    let flags = false;
    for (let i = 0; i < wraplyric.length; i++) {
      const isWrap = useIsTextWrap(wraplyric[i], style);
      console.log(`${wraplyric[i]},isWrap:${isWrap}`);
      if (isWrap) {
        flags = true;
        let fontSize = parseInt(style.fontSize);
        style.fontSize = --fontSize + "px";
        break;
      }
    }
    if (!flags) {
      return style.fontSize;
    }
  }
}
